<!--字典类型-->
<script setup lang="ts">
interface User {
  name: string;
  code: string;
  status: boolean;
}
const tableRowClassName = ({ row, rowIndex }: { row: User; rowIndex: number }) => {
  if (!row.status) {
    return "warning-row";
  } else {
    return "";
  }
};
import {
  getDictTypePage,
  getDictTypeForm,
  addDictType,
  updateDictType,
  deleteDictTypes,
} from "@/api/dict";

import { DictTypePageVO, DictTypeQuery, DictTypeForm } from "@/api/dict/types";
import { Bottom, Close, CaretBottom, Plus } from '@element-plus/icons-vue'
defineOptions({
  name: "DictType",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const agentDialogVisible = ref(false)
const agentDialogVisible2 = ref(false)
const agentDialogVisible3 = ref(false)
const agentDialogVisible4 = ref(false)
const agentDialogVisible5 = ref(false)
const agentDialogVisible6 = ref(false)
const agentDialogVisible7 = ref(false)
const drawer = ref(false)
const drawer2 = ref(false)

const switchValue = ref(false); // 响应式变量保存开关状态
const switchValue2 = ref(false);

const queryParams = reactive<DictTypeQuery>({
  pageNum: 1,
  pageSize: 10,
});

//const dictTypeList = ref<DictTypePageVO[]>();
/* 静态表格字段 */
const dataList = ref([
  {
    name: '商户1',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户2',
    code: 'M100002',
    status: false,
  },
  {
    name: '商户3',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户4',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户5',
    code: 'M100001',
  },
  {
    name: '商户6',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户7',
    code: 'M100001',
  },
  {
    name: '商户8',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户9',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户10',
    code: 'M100002',
    status: true,
  },
]);
const handleSwitchChange = (row) => {
  const statusText = row.status ? "启用" : "禁用";
  ElMessage.success(`${statusText}成功`);
  // 这里可以添加状态切换的逻辑，例如发起请求等
  if (row.status === "禁用") {
    row.dimmed = true;
  } else {
    row.dimmed = false;
  }
};


const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<DictTypeForm>({
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: "请输入", trigger: "blur" }],
  code: [{ required: true, message: "请输入", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getDictTypePage(queryParams)
    .then(({ data }) => {
      dictTypeList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/* 重置密码 */
const open2 = () => {
  ElMessage({
    message: '密码重置成功',
    type: 'success',
  })
}
const showConfirmDialog2 = (confirmCallback: () => void) => {
  const handleConfirm = async () => {
    try {
      await this.$confirm("确定导出？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      // 用户点击了确认按钮
      confirmCallback();
    } catch (error) {
      // 用户点击了取消按钮或发生了其他错误
    }
  };
  return { handleConfirm };
};
const handleResetPassword = async () => {
  console.log("确认按钮被点击了");
  open2()
};


/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(dicTypeId?: number) {
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改字典类型";
    getDictTypeForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增字典类型";
  }
}

/** 字典类型表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictTypeId = formData.id;
      if (dictTypeId) {
        updateDictType(dictTypeId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addDictType(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭字典类型弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置字典类型表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除字典类型 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteDictTypes(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

const selectedDictType = reactive({ typeCode: "", typeName: "" }); // 当前选中的字典类型

/** 打开字典数据弹窗 */
function openDictDialog(row: DictTypePageVO) {
  dictDataDialog.visible = true;
  dictDataDialog.title = "【" + row.name + "】字典数据";

  selectedDictType.typeCode = row.code;
  selectedDictType.typeName = row.name;
}

/**  关闭字典数据弹窗 */
function closeDictDialog() {
  dictDataDialog.visible = false;
}

/* 分页 */
const currentPage4 = ref(4)
const pageSize4 = ref(100)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="" prop="name">
          <el-input v-model="queryParams.keywords" placeholder="代理ID/代理名称/登录账号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="" prop="name">
          <el-select v-model="value" clearable placeholder="代理状态" style="width: 100px;">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
          <el-button type="primary" @click="handleQuery()"><i-ep-search />搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div style="display: flex;justify-content: space-between;">
          <div class="left" style="width: 840px;height: 30px;">
            <span
              style="background-color: #e6fffb;color: #0897b3;border: 1px solid #87e8de;padding: 2px 3px;margin-right: 3px;">代理数量：17</span><span
              style="background-color: #fff0f6;color: #c41d7f;border: 1px solid #ffadd2;padding: 2px 3px;margin-right: 3px;">代理总余额：￥44837.28</span><span
              style="border: 1px solid lightgray;padding: 2px 3px;">代理总冻结金额：¥120.00</span>
          </div>
          <div class="right" style="width: 300px;">
            <el-button type="primary" style="float:right;" @click="drawer = true">
              <el-icon style="margin-right:10px;">
                <Plus />
              </el-icon>
              创建代理</el-button>
          </div>
        </div>

      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="dataList"
        border
        class="tabs"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="代理名称" prop="name" min-width="110" />
        <el-table-column label="登录账号" prop="code" min-width="110" />
        <el-table-column label="代理账户" prop="remark" align="left" min-width="200">
          <template #default="scope">
            <div style="display: flex;justify-content: space-between;">
              <div style="display: inline-grid;">
                <span style="color: orange;font-weight: bold;height: 18px;">余额：¥<span>0.00</span></span>
                <span style="height: 18px;">冻结：¥<span>0.00</span></span>
              </div>
              <div class="right">
                <p style="color: #1890ff;margin-top: -3px;">提现</p>
                <div>
                  <el-dropdown :hide-on-click="false" :split-button="false" class="no-border-dropdown">
                    <span class="el-dropdown-link" style="color: #1890ff;">
                      ...<el-icon class="el-icon--right">
                        <CaretBottom />
                      </el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>

                        <el-dropdown-item><span style="padding: 2px 8px;background-color: gray;color: white;"
                            @click="agentDialogVisible = true">扣 除</span> </el-dropdown-item>
                        <el-dropdown-item><span style="padding: 2px 8px;background-color: red;color: white;"
                            @click="agentDialogVisible2 = true">冻 结</span> </el-dropdown-item>
                        <el-dropdown-item><span style="padding: 2px 8px;background-color: #1890ff;color: white;"
                            @click="agentDialogVisible3 = true">解 冻</span> </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>

              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="代理状态" align="center" min-width="130">
          <template #default="{ row }">  
        <el-switch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用" @change="handleSwitchChange(row)" />  
      </template>  
        </el-table-column>
        <el-table-column label="代理商户" prop="code" min-width="170">
          <p @click="agentDialogVisible4 = true" class="shanghu">【商户】</p>
        </el-table-column>

        <el-table-column label="代理支付通道" prop="remark" align="left" min-width="170">
          <template #default="scope">
            <div style="display: flex;" @click="agentDialogVisible6 = true" class="paytongdao">
              -
            </div>
          </template>
        </el-table-column>

        <el-table-column label="代理代付通道" prop="remark" align="left" min-width="170">
          <template #default="scope">
            <div style="display: flex;" @click="agentDialogVisible5 = true" class="exchangetongdao">
              -
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="140">
          <template #default="scope">
            <div style="display: flex;">

              <el-popconfirm title="确定重置该代理密码?" width="230px" @confirm="handleResetPassword">
                <template v-slot:reference="{ confirm }">
                  <el-button type="primary" link size="small" @click.stop="showConfirmDialog2(confirm)" style="font-size: 16px;">
                    重置登录密码
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
            <div>
              <el-button v-hasPerm="['sys:dict_type:edit']" type="primary" link size="small"
                style="font-size: 16px;" @click="drawer2=true">编辑</el-button>
              <el-button v-hasPerm="['sys:dict_type:delete']" type="primary" link size="small"
                style="font-size: 16px;color: red;"  @click="agentDialogVisible7=true">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery"
        layout="->,total, sizes, prev, pager, next, jumper" />
      <div class="demo-pagination-block" style="float: right;">
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
          :page-sizes="[100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="400" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" style="margin-top: 10px;"/>
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="closeDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="字典类型备注"
            :autosize="{ minRows: 2, maxRows: 4 }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--字典数据弹窗-->
    <el-dialog v-model="dictDataDialog.visible" :title="dictDataDialog.title" width="1000px" @close="closeDictDialog">
      <dict-item v-model:typeCode="selectedDictType.typeCode" v-model:typeName="selectedDictType.typeName" />
    </el-dialog>

    <!--  扣除-->
    <el-dialog v-model="agentDialogVisible" title="扣除" width="550px">
      <deduct-item />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button @click="agentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="agentDialogVisible = false">
          确认
        </el-button>
      </span>
    </el-dialog>
    <!-- 冻结 -->
    <el-dialog v-model="agentDialogVisible2" title="冻结" width="550px">
      <freeze-item />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button @click="agentDialogVisible2 = false">取消</el-button>
        <el-button type="primary" @click="agentDialogVisible2 = false">
          确认
        </el-button>
      </span>
    </el-dialog>
    <!-- 解冻 -->
    <el-dialog v-model="agentDialogVisible3" title="解冻" width="550px">
      <unfreeze-item />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button @click="agentDialogVisible3 = false">取消</el-button>
        <el-button type="primary" @click="agentDialogVisible3 = false">
          确认
        </el-button>
      </span>
    </el-dialog>

    <!-- 代理商户 -->
    <el-dialog v-model="agentDialogVisible4" title="代理：【商户】" width="550px">
      <agency-item />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button type="primary" @click="agentDialogVisible4 = false">
          知道了
        </el-button>
      </span>
    </el-dialog>

    <!-- 代理代付通道 -->
    <el-dialog v-model="agentDialogVisible5" title="代理：【商户】" width="550px">
      <pay-agent />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button type="primary" @click="agentDialogVisible5 = false">
          知道了
        </el-button>
      </span>
    </el-dialog>

    <!-- 代理代付通道 -->
    <el-dialog v-model="agentDialogVisible6" title="代理：【商户】" width="550px">
      <agency-pay />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button type="primary" @click="agentDialogVisible6 = false">
          知道了
        </el-button>
      </span>
    </el-dialog>


    <!-- 抽屉新增 -->
    <el-drawer v-model="drawer" title="创建代理" :with-header="false">
      <el-form ref="" :model="formData2" :rules="rules" label-width="80px">
        <p
          style="margin-top: -5px;font-size: 17px;font-weight: 400;display: flex;align-items: center;height: 50px;border-bottom: 1px solid lightgray;">
          <el-icon @click="closeDrawer" color="gray" style="margin-right: 5px;">
            <Close />
          </el-icon>创建代理
        </p>
        <el-form-item label="代理名称" prop="name" style="display: flex;align-items: center;"> <el-input v-model="input1"
            class="w-50 m-2" size="large" placeholder="请输入商户名称" style="width: 300px;" /></el-form-item>
        <el-form-item label="登录账号" prop="code" style="display: flex;align-items: center;"> <el-input v-model="input1"
            class="w-50 m-2" size="large" placeholder="请输入登录账号(4-20位字母或数字)" style="width: 300px;" /></el-form-item>

        <p style="display: flex;justify-content: flex-end;padding-top: 10px;position: fixed;bottom: 0px;right: 10px;">
          <el-button @click="closeDrawer">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </p>
      </el-form>
    </el-drawer>

    <!-- 编辑代理 -->
    <el-drawer v-model="drawer2" title="编辑代理" :with-header="false">
      <el-form ref="" :model="formData2" :rules="rules" label-width="80px">
        <p
          style="margin-top: -5px;font-size: 17px;font-weight: 400;display: flex;align-items: center;height: 50px;border-bottom: 1px solid lightgray;">
          <el-icon @click="drawer2=false" color="gray" style="margin-right: 5px;">
            <Close />
          </el-icon>编辑代理
        </p>
        <el-form-item label="代理名称" prop="name" style="display: flex;align-items: center;"> <el-input v-model="input1"
            class="w-50 m-2" size="default" placeholder="请输入代理名称" style="width: 300px;" /></el-form-item>
        <el-form-item label="登录账号" prop="code" style="display: flex;align-items: center;"> <el-input v-model="input1"
            class="w-50 m-2" size="default" placeholder="请输入登录账号(4-20位字母或数字)" style="width: 300px;" /></el-form-item>
        <el-form-item label="默认币种" prop="code" style="display: flex;align-items: center;">
          <el-select v-model="value3" class="" placeholder="请选择支付产品" size="default"
            style="width: 300px;margin-left:10px">
            <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="代理状态" prop="" style="display: flex;align-items: center;">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              @change="handleSwitchChange(row)"
            />
          </template>
        </el-form-item>
        <el-form-item label="谷歌验证" prop="" style="display: flex;align-items: center;">
          <el-switch v-model="switchValue2" inline-prompt active-text="启用" inactive-text="禁用"
            style="margin-left:10px" />
        </el-form-item>

        <p style="display: flex;justify-content: flex-end;padding-top: 10px;position: fixed;bottom: 0px;right: 10px;">
          <el-button @click="closeDrawer">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </p>
      </el-form>
    </el-drawer>

    <!-- 删除 -->
    <el-dialog v-model="agentDialogVisible7" title="删除代理" width="500px">
      <agency-delete />
      <span class="dialog-footer" style="margin-top:20px;display:flex;justify-content:flex-end">
        <el-button @click="agentDialogVisible7 = false">取消</el-button>
        <el-button type="primary" @click="agentDialogVisible7 = false">
          确认
        </el-button>
      </span>
    </el-dialog>

  </div>
</template>

<style lang="scss" scoped>
.app-container {
  height: 100%;

  .table-container {
    height: 100%;
    //background-color: pink;

    .tabs {
      height: calc(100vh - 265px);
      overflow-y: auto;
    }

  }
}

.shanghu:hover{
  cursor: pointer;
}
.exchangetongdao{
  cursor: pointer;
}
.paytongdao{
  cursor:pointer
}
::v-deep(.warning-row) {
  opacity: 0.5;
}
</style>